import http from '@/api/http.js'

const toutiaoPay = function(orderData, successFun = '', failFun = '') {
	let toutiaoTrade = uni.getStorageSync('cfg_toutiao_trade_is_open');
	if (toutiaoTrade == 1) {
		tradePay(orderData, successFun, failFun)
	} else {
		normalPay(orderData, successFun, failFun)
	}
}

/**
 * 交易2.0
 */
const tradePay = function(orderData, successFun = '', failFun = '') {
	let params = {
		method: 'api/v2/toutiao/trade/get_trade_options',
		ordersn: orderData.ordersn
	};
	uni.showLoading({
		title: '正在发起支付'
	});
	http(params).then(res => {
		uni.hideLoading();
		if (res.status) {
			if (res.step == 1) {
				tradeCreateOrder(res.data.options, successFun, failFun)
			} else {
				continueToPay(res.data.outOrderNo, successFun, failFun)
			}
		} else {
			let data = res.data;
			// 如果是已支付 或者 0元支付成功回调
			if (data.sign) {
				if (data.sign == 24 && data.id) { // 支付成功
					uni.redirectTo({
						url: `/pages/order/paysuccess?ordersn=${data.ordersn}&orderid=${data.id}`
					})
					return;
				} else {
					tt.showToast({
						title: res.data,
						icon: 'fail'
					});
				}
			} else {
				tt.showToast({
					title: res.data,
					icon: 'fail'
				});
			}
		}
	})
}


const tradeCreateOrder = function(options, successFun = '', failFun = '') {
	let skuList = options.skuList,
		goodsList = options.goodsList,
		payment = options.payment,
		contactInfo = options.contactInfo,
		note = options.note,
		businessLine = options.businessLine,
		callbackData = options.callbackData;
	let createOptions = {
		skuList: skuList,
		goodsList: goodsList,
		payment: payment,
		contactInfo: contactInfo,
		note: note, // 备注 非必传
		callbackData: callbackData, // 透传数据，开发者自定义字段 非必传
		businessLine: businessLine,
		success: (res) => {
			const {
				orderId,
				outOrderNo
			} = res;
			if (successFun) {
				setTimeout(() => {
					successFun();
				}, 2000);
			}
		},
		fail: (res) => {
			const {
				orderId,
				outOrderNo,
				errNo,
				errMsg,
				errLogId
			} = res;
			let showMsg = '支付取消';
			if (errLogId) {
				console.log("预下单失败", errNo, errMsg, errLogId);
			}
			if (orderId || outOrderNo) {
				console.log("支付失败", errNo, errMsg, orderId, outOrderNo);
			}
			uni.showToast({
				title: showMsg,
				icon: 'none',
				duration: 2000
			});
			// 失败执行事件
			if (failFun) {
				setTimeout(() => {
					failFun();
				}, 2000);
			}

		},
	}
	console.log(createOptions);
	tt.createOrder(createOptions);
}

const continueToPay = function(outOrderNo, successFun = '', failFun = '') {
	tt.continueToPay({
		outOrderNo, // 外部订单号 2个订单号必填一个
		success: (res) => {
			const {
				orderId,
				outOrderNo
			} = res;
			if (successFun) {
				setTimeout(() => {
					successFun();
				}, 2000);
			}
			console.log("success res", res);
			console.log("orderId", orderId, "outOrderNo", outOrderNo);
		},
		fail: (res) => {
			const {
				orderId,
				outOrderNo,
				errNo,
				errMsg,
				errLogId
			} = res;
			let showMsg = '支付取消';
			if (errLogId) {
				console.log("预下单失败", errNo, errMsg, errLogId);
			}
			if (orderId || outOrderNo) {
				console.log("支付失败", errNo, errMsg, orderId, outOrderNo);
			}
			uni.showToast({
				title: showMsg,
				icon: 'none',
				duration: 2000
			});
			// 失败执行事件
			if (failFun) {
				setTimeout(() => {
					failFun();
				}, 2000);
			}
		},
	});
}

/**
 * 原有的收银台和担保交易
 */
const normalPay = function(orderData, successFun = '', failFun = '') {
	let ordersn = orderData.ordersn,
		orderid = orderData.orderid,
		cfgByte = uni.getStorageSync('cfg_toutiao_danbao_status') ? uni.getStorageSync(
			'cfg_toutiao_danbao_status') : 0,
		pageType = orderData.pageType ? orderData.pageType : 0; // 页面跳转模式 默认0为直接跳转 1为关闭当前页面跳转
	let params = {
		ordersn: ordersn
	};
	if (cfgByte == 1) {
		params.method = 'api/v2/payment/toutiao/create_order'
	} else {
		params.method = 'api/v2/payment/toutiao/get_pay_data'
	}
	uni.showLoading({
		title: '正在发起支付'
	});
	http(params).then(payRes => {
		uni.hideLoading();
		if (payRes.status) {
			let orderInfo,
				service = (cfgByte == 1) ? 5 : 1;
			if (cfgByte == 1) {
				orderInfo = payRes.data
			} else {
				let payResult = payRes.data;
				//组装头条支付信息
				orderInfo = {
					merchant_id: payResult.merchant_id,
					app_id: payResult.app_id,
					sign_type: payResult.sign_type,
					timestamp: payResult.timestamp,
					version: payResult.version,
					trade_type: payResult.trade_type,
					sign: payResult.sign,
					product_code: payResult.product_code,
					payment_type: payResult.payment_type,
					out_order_no: payResult.out_order_no,
					uid: payResult.uid,
					total_amount: payResult.total_amount,
					currency: payResult.currency,
					subject: payResult.subject,
					body: payResult.body,
					trade_time: payResult.trade_time,
					valid_time: payResult.valid_time,
					notify_url: payResult.notify_url,
					alipay_url: payResult.alipay_url,
					wx_url: payResult.wx_url,
					wx_type: payResult.wx_type,
					risk_info: payResult.risk_info,
				}
			}

			uni.requestPayment({
				provider: 'toutiao',
				orderInfo,
				service,
				getOrderStatus: (statusRes) => {
					let out_order_no = statusRes.out_order_no;
					return new Promise(function(resolve, reject) {
						let params = {
							method: 'api/v2/payment/toutiao/query_order_status',
							ordersn: out_order_no
						};
						http(params).then(res => {
							if (res.data == 2) {
								resolve({
									code: 0
								})
							}
						})
					})
				},
				success(res) {
					if (res.code == 0) {
						// 支付成功处理逻辑，只有res.code=0时，才表示支付成功
						// 成功执行事件
						if (successFun) {
							setTimeout(() => {
								successFun();
							}, 2000);
						}
					}

				},
				'fail': function(data) {
					uni.showToast({
						title: "支付已取消",
						icon: 'none',
						duration: 2000
					});
					// 失败执行事件
					if (failFun) {
						setTimeout(() => {
							failFun();
						}, 2000);
					}
				}

			})
		} else {

			let data = payRes.data;
			// 如果是已支付 或者 0元支付成功回调
			if (data.sign) {
				if (data.sign == 24 && data.id) { // 支付成功
					uni.redirectTo({
						url: `/pages/order/paysuccess?ordersn=${data.ordersn}&orderid=${data.id}`
					})
					return;
				} else {
					tt.showToast({
						title: payRes.msg,
						icon: 'fail'
					});
				}
			} else {
				tt.showToast({
					title: payRes.msg,
					icon: 'fail'
				});
			}
		}
	});
}


export default toutiaoPay
